package com.helloandroid.activitys

import android.app.AlertDialog
import android.app.NativeActivity
import android.content.DialogInterface
import android.content.Intent
import android.widget.ImageButton
import android.widget.TextView
import androidx.core.content.edit
import com.helloandroid.R
import com.helloandroid.ads.NativeAdUtil
import com.helloandroid.ads.SmallNativeAdUtil
import com.helloandroid.base.BaseActivity
import com.helloandroid.dialogs.IValueChange
import com.helloandroid.dialogs.SinglePicker
import com.helloandroid.tools.MyLog

class BodyInfoActivity : BaseActivity() {

    companion object {
        const val KeyShareFile = "body_info"
        const val KeySex = "sex"
        const val KeyAge = "age"
        const val KeyHeight = "height"
        const val KeyWeight = "weight"
        const val BMI_Min = 18.5f
        const val BMI_Max = 23.9f
        const val BMI_Super = 28.0f

        val SexItems = arrayOf<String>("男", "女")

        // 一些默认值 // 0表示男  1表示女
        const val DefaultSex = 0
        const val DefaultAge = 20
        const val DefaultHeight = 170
        const val DefaultWeight = 120

        val AgeLst = generateSequence(5) { it + 1 }.takeWhile { it <= 120 }.toList()
        val HeightLst = generateSequence(20) { it + 1 }.takeWhile { it <= 250 }.toList()
        val WeightLst = generateSequence(2){it + 1}.takeWhile { it <= 500 }.toList()
    }

    private val ageListener = IValueChange<Int> { newValue ->
        age = newValue
        tvAge.text = "$newValue"
        val pref = getSharedPreferences(KeyShareFile, MODE_PRIVATE)
        pref.edit(commit = true) {
            putInt(KeyAge, newValue)
        }
    }

    private val heightListener = IValueChange<Int> { newValue ->
        height = newValue
        tvHeight.text = "$newValue"
        val pref = getSharedPreferences(KeyShareFile, MODE_PRIVATE)
        pref.edit(commit = true) {
            putInt(KeyHeight, newValue)
        }
        updateBMI()
    }

    private val weightListener = IValueChange<Int> { newValue ->
        weight = newValue
        tvWeight.text = "$weight"
        val pref = getSharedPreferences(KeyShareFile, MODE_PRIVATE)
        pref.edit(commit = true) {
            putInt(KeyWeight, newValue)
        }
        updateBMI()
    }

    lateinit var tvSex: TextView
    lateinit var tvBMI: TextView
    lateinit var tvAge: TextView
    lateinit var tvHeight: TextView
    lateinit var tvWeight: TextView

    private var sex: Int = 0
    private var age: Int = 0
    private var height: Int = 0
    private var weight: Int = 0

    override fun getContentViewResId() = R.layout.activity_bodyinfo

    override fun initView() {
        tvSex = findViewById(R.id.tvSex)
        tvBMI = findViewById(R.id.tvBMI)
        tvAge = findViewById(R.id.tvAge)
        tvHeight = findViewById(R.id.tvHeight)
        tvWeight = findViewById(R.id.tvWeight)
        findViewById<ImageButton>(R.id.ibBack).setOnClickListener { finish() }

        // 还需要记录上一次的
        val pref = getSharedPreferences(KeyShareFile, MODE_PRIVATE)

        sex = pref.getInt(KeySex, DefaultSex)
        age = pref.getInt(KeyAge, DefaultAge)
        height = pref.getInt(KeyHeight, DefaultHeight)
        weight = pref.getInt(KeyWeight, DefaultWeight)

        tvSex.text = if (sex == 0) "男" else "女"
        tvAge.text = "$age"
        tvHeight.text = "$height 厘米"
        tvWeight.text = "$weight 斤"
        updateBMI()

        // 选择性别
        findBtn(R.id.btnSex).setOnClickListener {
            AlertDialog.Builder(this)
                    .setTitle("请选择性别")
                    .setSingleChoiceItems(SexItems, sex) { dia, i ->
                        MyLog.elog("i : $i")
                        sex = i
                        tvSex.text = if (sex == 0) "男" else "女"
                        pref.edit(commit = true) {
                            putInt(KeySex, sex)
                        }
                        dia.dismiss()
                    }.create().show()
        }

        //  选择年龄
        findBtn(R.id.btnAge).setOnClickListener {
            val agePicker = SinglePicker<Int>(this, age, AgeLst)
            agePicker.valueChangeListener = ageListener
            agePicker.title = "请选择年龄"
            agePicker.show()
        }

        // 选择身高
        findBtn(R.id.btnHeight).setOnClickListener {
            val heightPicker = SinglePicker<Int>(this, height, HeightLst)
            heightPicker.title = "请选择身高(厘米)"
            heightPicker.valueChangeListener = heightListener
            heightPicker.show()
        }

        // 选择体重
        findBtn(R.id.btnWeight).setOnClickListener {
            val weightPicker = SinglePicker<Int>(this,weight,WeightLst)
            weightPicker.title = "请选择体重(斤)"
            weightPicker.valueChangeListener = weightListener
            weightPicker.show()
        }

        // 查看 BMI
        findBtn(R.id.btnBMI).setOnClickListener {
            val intent = Intent(this,BMIInfoActivity::class.java)

            val bmiValue = calBMI()
            val bmi = (bmiValue * 100).toInt() / 100f
            intent.putExtra("bmi",bmi)
            intent.putExtra("bmi_state",getBMIState(bmiValue))
            startActivity(intent)
        }

        // 查看身体报告
        findBtn(R.id.btnBodyInfo).setOnClickListener {
            val intent = Intent(this,BodyResultActivity::class.java)

            val bmiValue = calBMI()
            val bmi = (bmiValue * 100).toInt() / 100f
            intent.putExtra("bmi",bmi)
            intent.putExtra("bmi_state",getBMIState(bmiValue))

            // 再用1.2xBMI值+0.23x年龄-5.4-10.8x性别，男女性别分别用1和0代替。
            // 计算体脂
            val tz:Float = 1.39f * bmi + 0.16f * age - 10.34f * (if(sex == 1)1 else 0) - 9f
            MyLog.elog("体脂率:$tz")
            intent.putExtra("tz",tz)
            intent.putExtra("sex",sex)
            startActivity(intent)
        }

        SmallNativeAdUtil.showNativeAd(this,findViewById(R.id.nativeView))
    }

    override fun initData() {
    }

    // 体质指数（BMI）计算公式=体重（千克）除以身高（平方米）。
    //BMI指数（即身体质量指数，简称体质指数又称体重，英文为BodyMassIndex，简称BMI），
    // 是用体重公斤数除以身高米数平方得出的数字，是目前国际上常用的衡量人体胖瘦程度以及是否健康的一个标准。BMI的正常范围为18.5-23.9
    private fun calBMI():Float = 5000f * weight / (height * height)

    private fun updateBMI() {
        val bmiValue = calBMI()
        val bmiStr = String.format("%.2f", bmiValue)
        val bmiState = getBMIState(bmiValue)
        tvBMI.text = "$bmiStr $bmiState"
    }

    fun getBMIState(bmiValue:Float):String{
        return when {
            bmiValue < BMI_Min ->"偏瘦"
            bmiValue in BMI_Min..BMI_Max -> "理想"
            bmiValue > BMI_Max && bmiValue < BMI_Super -> "偏胖"
            bmiValue >= BMI_Super -> "肥胖"
            else -> "Unknow"
        }
    }

    override fun isUseFullScreenMode() = true

}